﻿using System.Globalization;
using System.Text;

namespace ShareHelper
{
    /// <summary>
    ///
    /// </summary>
    public static class HexHelper
    {
        /// <summary>
        ///  byte 到 十六进制文本
        /// </summary>
        /// <param name="data">byte 数组集合</param>
        /// <param name="separate">分隔符</param>
        /// <param name="Lower">是否小写 默认为true 小写</param>
        /// <returns></returns>
        public static string ByteToHexStr(this byte[] data, string separate, bool Lower = true)
        {
            if (data?.Length < 1) return string.Empty;
            if (string.IsNullOrEmpty(separate)) return ByteToHexStr(data, Lower);
            var sb = new StringBuilder();
            var a = Lower ? 0x61 : 0x41;
            for (int i = 0; i < data.Length; i++)
            {
                var b = data[i];
                sb.Append(GetHexValue(b / 0x10, a));
                sb.Append(GetHexValue(b % 0x10, a));
                sb.Append(separate);
            }
            return sb.ToString();
        }

        /// <summary>
        /// byte 到 十六进制文本
        /// </summary>
        /// <param name="data">byte 数组集合</param>
        /// <param name="Lower">是否小写 默认为true 小写</param>
        /// <returns></returns>
        public static string ByteToHexStr(this byte[] data, bool Lower = true)
        {
            if (data?.Length < 1) return string.Empty;
            var a = Lower ? 0x61 : 0x41;
            var cs = new char[data.Length * 2];
            for (int i = 0, j = 0; i < data.Length; i++, j += 2)
            {
                var b = data[i];
                cs[j] = GetHexValue(b / 0x10, a);
                cs[j + 1] = GetHexValue(b % 0x10, a);
            }
            return new string(cs);
        }

        private static char GetHexValue(int i, int a)
        {
            if (i < 10)
                return (char)(i + 0x30);
            else
                return (char)(i - 10 + a);
        }

        /// <summary>
        /// 十六进制文本到 byte 集合
        /// </summary>
        /// <param name="hexString">十六进制文本</param>
        /// <returns></returns>
        public static byte[] HexStrToByte(this string hexString)
        {
            //替换空格 换行
            hexString = hexString.Trim()
             .Replace("-", null)
             .Replace("0x", null)
             .Replace("0X", null)
             .Replace(" ", null)
             .Replace("\r", null)
             .Replace("\n", null)
             .Replace(",", null);
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = byte.Parse(hexString.Substring(i * 2, 2), NumberStyles.HexNumber);
            return returnBytes;
        }
    }
}